const sql = require("../../mysql");
const config = require("../../config");
const jwt = require("jsonwebtoken");
const md5 = require("md5");

module.exports = async ctx => {
  try {
    const { uname, password } = ctx.request.body;

    let user = await sql.User.findOne({
      where: {
        uname
      }
    });

    if (!user) {
      ctx.body = {
        code: -1,
        msg: "用户名或者密码错误"
      };
      return;
    }
    if (!user.status) {
      ctx.body = {
        code: -1,
        msg: "用户已被禁用，联系管理员解除禁用"
      };
      return;
    }
    if (user.password === md5(md5(password))) {
      const token = await jwt.sign(
        { id: user.id, uname, role: user.role },
        config.secret,
        {
          expiresIn: "1day"
        }
      );
      ctx.body = {
        code: 0,
        data: {
          token
        }
      };
    } else {
      ctx.body = {
        code: -1,
        msg: "用户名密码错误"
      };
    }
  } catch (error) {
    ctx.body = {
      code: -1,
      msg: error.errors[0].message
    };
  }
};
